package dom;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;

public class XMLParse {
    Document doc=null;
    public void getDocument(){
        // 获取解析器工厂
        DocumentBuilderFactory dbf=DocumentBuilderFactory.newInstance();

        // 获取解析器
        try {
            DocumentBuilder bd=dbf.newDocumentBuilder();
            doc= bd.parse("src/main/resources/phone.xml");
        } catch (ParserConfigurationException e) {
            e.printStackTrace();;
        } catch (IOException e) {
            e.printStackTrace();
        } catch (SAXException e) {
            e.printStackTrace();
        }
    }

    public void showInfo(){
        // 获取<Brand>的所有节点集合
        NodeList nodeList=doc.getElementsByTagName("Brand");
        for (int i = 0; i < nodeList.getLength(); i++) {
            Node brand=nodeList.item(i);
            Element brandEle=(Element) brand;
            String brandStr=brandEle.getAttribute("name");
            NodeList types=brandEle.getChildNodes();
            for (int j = 0; j < types.getLength(); j++) {
                Node type=types.item(j);
                if (type.getNodeType()==Node.ELEMENT_NODE){
                    Element typeEle=(Element) type;
                    String typeStr=typeEle.getAttribute("name");
                    System.out.println("手机："+brandStr+typeStr);
                }
            }
        }
    }

    public static void main(String[] args) {
        XMLParse parse=new XMLParse();
        parse.getDocument();
        parse.showInfo();
    }
}
